package com.example.campusannouncement.service;

import com.example.campusannouncement.repository.AnnouncementRepository;
import com.example.campusannouncement.entity.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class AnnouncementService {
    @Autowired
    private AnnouncementRepository announcementRepository;

    //获取所有公告（分页）
    public Page<Announcement> getAllAnnouncements(Pageable pageable) {
        return announcementRepository.findAll(pageable);
    }

    //搜索公告
    public Page<Announcement> searchAnnouncements(String keyword, Pageable pageable) {
        return announcementRepository.findByTitleContainingOrContentContaining(keyword, keyword, pageable);
    }

    //根据ID获取单个公告
    public Optional<Announcement> getAnnouncementById(Long id) {
        return announcementRepository.findById(id);
    }

    // 创建公告
    public Announcement createAnnouncement(Announcement announcement) {
        // 设置默认发布日期为当前时间
        if (announcement.getPublishDate() == null) {
            announcement.setPublishDate(new Date());
        }
        // 设置创建时间和更新时间
        Date now = new Date();
        announcement.setCreatedAt(now);
        announcement.setUpdatedAt(now);
        return announcementRepository.save(announcement);
    }

    //更新公告
    public Announcement updateAnnouncement(Long id, Announcement updatedAnnouncement) {
        return announcementRepository.findById(id)
                .map(announcement -> {
                    announcement.setTitle(updatedAnnouncement.getTitle());
                    announcement.setContent(updatedAnnouncement.getContent());
                    announcement.setAuthor(updatedAnnouncement.getAuthor());
                    announcement.setPublishDate(updatedAnnouncement.getPublishDate());
                    announcement.setStatus(updatedAnnouncement.getStatus());
                    announcement.setAttachmentPath(updatedAnnouncement.getAttachmentPath());
                    // 更新修改时间
                    announcement.setUpdatedAt(new Date());
                    return announcementRepository.save(announcement);
                })
                .orElseThrow(() -> new RuntimeException("Announcement not found with id: " + id));
    }

    //删除公告
    public void deleteAnnouncement(Long id) {
        if (!announcementRepository.existsById(id)) {
            throw new RuntimeException("Announcement not found with id: " + id);
        }
        announcementRepository.deleteById(id);
    }

    //批量删除公告
    public void deleteAnnouncements(List<Long> ids) {
        announcementRepository.deleteAllById(ids);
    }
}